package com.grade.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.grade.common.constant.Constants;
import com.grade.common.core.domain.entity.SysRole;
import com.grade.common.utils.DateUtils;
import com.grade.system.domain.*;
import com.grade.system.mapper.GradeItemMapper;
import com.grade.system.mapper.GradeTypeMapper;
import com.grade.system.mapper.ItemTemplateRelationMapper;
import org.apache.commons.collections.ArrayStack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.grade.system.mapper.GradeTemplateMapper;
import com.grade.system.service.IGradeTemplateService;
import com.grade.common.core.text.Convert;

/**
 * 评分模板Service业务层处理
 * 
 * @author grade
 * @date 2021-10-17
 */
@Service
public class GradeTemplateServiceImpl implements IGradeTemplateService 
{
    @Autowired
    private GradeTemplateMapper gradeTemplateMapper;
    @Autowired
    private ItemTemplateRelationMapper itemTemplateRelationMapper;
    @Autowired
    private GradeItemMapper gradeItemMapper;
    @Autowired
    private GradeTypeMapper gradeTypeMapper;

    /**
     * 查询评分模板
     * 
     * @param id 评分模板主键
     * @return 评分模板
     */
    @Override
    public GradeTemplate selectGradeTemplateById(Long id)
    {
        return gradeTemplateMapper.selectGradeTemplateById(id);
    }

    /**
     * 查询评分模板列表
     * 
     * @param gradeTemplate 评分模板
     * @return 评分模板
     */
    @Override
    public List<GradeTemplate> selectGradeTemplateList(GradeTemplate gradeTemplate)
    {
        return gradeTemplateMapper.selectGradeTemplateList(gradeTemplate);
    }

    /**
     * 新增评分模板
     * 
     * @param gradeTemplate 评分模板
     * @return 结果
     */
    @Override
    public int insertGradeTemplate(GradeTemplate gradeTemplate)
    {
        gradeTemplate.setCreateTime(DateUtils.getNowDate());
        gradeTemplate.setLayer(0);
        //判断是否引用已有的模版
        if (gradeTemplate.getTemplateId()!=null && !gradeTemplate.getTemplateId().equals("")){
            //更新模版层级
            GradeTemplate copyGradeTemplate=selectGradeTemplateById(Long.parseLong(gradeTemplate.getTemplateId()));
            if (copyGradeTemplate!=null){
                gradeTemplate.setLayer(copyGradeTemplate.getLayer());
            }
        }
        gradeTemplateMapper.insertGradeTemplate(gradeTemplate);
        Long templateId=gradeTemplate.getId();


        if (gradeTemplate.getTemplateId()!=null && !gradeTemplate.getTemplateId().equals("")){
            //递归复制模版评分类型和评分细则
            Long typeId;
            List<GradeType> gradeTypeList=gradeTypeMapper.selectTopGradeTypeByTemplateId(Long.parseLong(gradeTemplate.getTemplateId()));
            for (int i=0;i<gradeTypeList.size();i++){
                //复制顶级目录类型
                GradeType gradeType=gradeTypeList.get(i);
                typeId=gradeType.getTypeId();
                gradeType.setTemplateId(templateId);
                gradeType.setCreateTime(DateUtils.getNowDate());
                gradeType.setUpdateTime(null);
                gradeTypeMapper.insertGradeType(gradeType);

                //复制顶级目录评分类型下的评分细则
                List<GradeItem> gradeItemList=gradeItemMapper.selectGradeItemByTypeId(typeId);
                for(int j=0;j<gradeItemList.size();j++){
                    GradeItem gradeItem=gradeItemList.get(j);
                    gradeItem.setTemplateId(templateId);
                    gradeItem.setTypeId(gradeType.getTypeId());
                    gradeItem.setCreateTime(DateUtils.getNowDate());
                    gradeItem.setUpdateTime(null);
                    gradeItemMapper.insertGradeItem(gradeItem);
                }

                //递归复制模版评分类型及细则
                copyGradeTypeItem(templateId,typeId,gradeType.getTypeId());
            }
        }
        return 1;
        //return insertTemplateItem(gradeTemplate);
    }

    /**
     * 复制模版评分类型及细则
     *
     * @param templateId 新插入的评分模版ID
     * @param parentId 引用模版的评分类型ID
     * @param typeId 新插入的评分类型ID
     */
    private void copyGradeTypeItem(long templateId,long parentId,long typeId){
        List<GradeType> childGradeTypeList=gradeTypeMapper.selectGradeTypeByParentId(parentId);
        Long childTypeId;
        for(int i=0;i<childGradeTypeList.size();i++){
            //复制评分类型
            GradeType gradeType=childGradeTypeList.get(i);
            childTypeId=gradeType.getTypeId();
            gradeType.setTemplateId(templateId);
            gradeType.setParentId(typeId);
            gradeType.setCreateTime(DateUtils.getNowDate());
            gradeType.setUpdateTime(null);
            gradeTypeMapper.insertGradeType(gradeType);

            //复制评分细则
            List<GradeItem> gradeItemList=gradeItemMapper.selectGradeItemByTypeId(childTypeId);
            for(int j=0;j<gradeItemList.size();j++){
                GradeItem gradeItem=gradeItemList.get(j);
                gradeItem.setTemplateId(templateId);
                gradeItem.setTypeId(gradeType.getTypeId());
                gradeItem.setCreateTime(DateUtils.getNowDate());
                gradeItem.setUpdateTime(null);
                gradeItemMapper.insertGradeItem(gradeItem);
            }

            //递归子评分类型及细则
            copyGradeTypeItem(templateId,childTypeId,gradeType.getTypeId());
        }
    }


    /**
     * 新增角色菜单信息
     *

     */
    public int insertTemplateItem(GradeTemplate gradeTemplate)
    {
        int rows = 1;
        List<GradeItem> allItemList = gradeItemMapper.selectItemAll();
        Map<Long,GradeItem> map= new HashMap<Long,GradeItem>();

        List<GradeType> allTypeList = gradeTypeMapper.selectGradeTypeAll();
        Map<Long,Long> childrenParentMap= new HashMap<Long,Long>();
        Map<Long,Integer> typeUseMap= new HashMap<Long,Integer>();

        Map<Long,String> typeNameMap= new HashMap<Long,String>();

        for(GradeItem item: allItemList){
            map.put(item.getId(),item);
        }

        for(GradeType gradeType: allTypeList){
            childrenParentMap.put(gradeType.getTypeId(),gradeType.getParentId());
            typeNameMap.put(gradeType.getTypeId(),gradeType.getTypeName());
            typeUseMap.put(gradeType.getTypeId(),0);
        }

        List<ItemTemplateRelation> list = new ArrayList<ItemTemplateRelation>();
        int maxLayer = 0;

        int orderNum = 0;
        for (Long itemId : gradeTemplate.getItemIds())
        {
            if(itemId> Constants.ID_ADD){
                Long reamItemId = itemId - Constants.ID_ADD;
                GradeItem gradeItem = map.get(reamItemId);
                ItemTemplateRelation itr = new ItemTemplateRelation();
                itr.setItemId(reamItemId);
                itr.setTemplateId(gradeTemplate.getId());
                itr.setTypeId(gradeItem.getTypeId());
                itr.setTypeName(typeNameMap.get(itr.getTypeId()));
                itr.setParentId(childrenParentMap.get(gradeItem.getTypeId()));
                itr.setParentTypeName(typeNameMap.get(itr.getParentId()));
                itr.setItemContent(gradeItem.getItemContent());
                itr.setMaxScore(gradeItem.getMaxScore());
                itr.setOrderNum(orderNum++);
                list.add(itr);
                int layer = getMaxColumnAndSetTypeName(itr, typeNameMap,childrenParentMap);
                maxLayer = maxLayer>layer?maxLayer:layer;
            }
        }

        GradeTemplate template = new GradeTemplate();
        template.setId(gradeTemplate.getId());
        template.setLayer(maxLayer);
        gradeTemplateMapper.updateGradeTemplate(template);

        rows = itemTemplateRelationMapper.batchItemTemplate(list);

        return rows;
    }

    private int getMaxColumnAndSetTypeName(ItemTemplateRelation itr,Map<Long,String> typeNameMap,Map<Long,Long>childrenParentMap){
        int maxColumn = 0;
        List<String>columonList = new ArrayList<String>();
        Long parentId = itr.getTypeId();
        do{
            maxColumn++;
            columonList.add(typeNameMap.get(parentId));
            parentId = childrenParentMap.get(parentId);
        }while(parentId>0);

        for(int i=1;i<=maxColumn;i++){
            if(i==1){
                itr.setFirstColumn(columonList.get(maxColumn-i));
            }else if(i==2){
                itr.setSecondColumn(columonList.get(maxColumn-i));
            }else if(i==3){
                itr.setThreeColumn(columonList.get(maxColumn-i));
            }else if(i==4){
                itr.setFourColumn(columonList.get(maxColumn-i));
            }else if(i==5){
                itr.setFiveColumn(columonList.get(maxColumn-i));
            }else if(i==6){
                itr.setSixColumn(columonList.get(maxColumn-i));
            }
        }
        return maxColumn;
    }

    private void markTypeUse(Long typeId,Map<Long,Long>childrenParentMap,Map<Long,Integer> typeUseMap){
        Long parentId = typeId;
        do{
            Integer useNumber = typeUseMap.get(parentId);
            typeUseMap.put(parentId,++useNumber);
            parentId= childrenParentMap.get(parentId);
        }while(parentId>0);
    }

    /**
     * 修改评分模板
     * 
     * @param gradeTemplate 评分模板
     * @return 结果
     */
    @Override
    public int updateGradeTemplate(GradeTemplate gradeTemplate)
    {
        gradeTemplate.setUpdateTime(DateUtils.getNowDate());
        return gradeTemplateMapper.updateGradeTemplate(gradeTemplate);
    }

    /**
     * 批量删除评分模板
     * 
     * @param ids 需要删除的评分模板主键
     * @return 结果
     */
    @Override
    public int deleteGradeTemplateByIds(String ids)
    {
        return gradeTemplateMapper.deleteGradeTemplateByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除评分模板信息
     * 
     * @param id 评分模板主键
     * @return 结果
     */
    @Override
    public int deleteGradeTemplateById(Long id)
    {
        return gradeTemplateMapper.deleteGradeTemplateById(id);
    }
}
